package com.supinfo.youfood.pages.magasin.view;

import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.List;

import javax.xml.rpc.ServiceException;

import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;

import com.supinfo.food.entities.Magasin;
import com.supinfo.food.services.MagasinService;
import com.supinfo.food.services.MagasinServiceService;
import com.supinfo.food.services.MagasinServiceServiceLocator;
import com.supinfo.youfood.template.Template;

/**
 * Liste des magasins
 * @author Keitaro
 */
public class MagasinView extends Template {

	private Logger logger = Logger.getLogger(getClass());
	
	private List<Magasin> listMagasins;
	
	public MagasinView() {
		callService();
		createTable();
	}
	
	/**
	 * Call the webservice
	 */
	private void callService() {
		try {
			MagasinServiceService binding = new MagasinServiceServiceLocator();
			MagasinService service = binding.getMagasinService();
			listMagasins = Arrays.asList(service.getAll());
		} catch (ServiceException e) {
			logger.info("Service can not be reached.");
		} catch (RemoteException e) {
			logger.info("Service does not responded.");
		}
	}

	/**
	 * Create table
	 * @return 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void createTable() {
		DataView dataView = new DataView("magasin", new ListDataProvider<>(
				listMagasins)) {
			private static final long serialVersionUID = 1L;

			public void populateItem(final Item item) {
                final Magasin magasin = (Magasin) item.getModelObject();
                item.add(new Label("id", String.valueOf(magasin.getId())));
                item.add(new Label("name", magasin.getName()));
                item.add(new Label("location", magasin.getLocation()));
                
                Link link = new Link("linkDeleteMagasin") {
					private static final long serialVersionUID = 1L;
					public void onClick() {
						// Appel au service
						try {
							MagasinServiceService binding = new MagasinServiceServiceLocator();
							MagasinService service = binding.getMagasinService();
							service.delete(magasin.getId());
						} catch (ServiceException e) {
							logger.info("Service can not be reached.");
						} catch (RemoteException e) {
							logger.info("Service does not responded.");
						}
						
						// Redirection
						setResponsePage(MagasinView.class);
					}
				};
				item.add(link);
            }
        };
        dataView.setItemsPerPage(10);
        add(dataView);
        add(new PagingNavigator("navigator", dataView));
	}
}
